package com.good.msgsys.interceptor;

import com.good.msgsys.dto.ResultCode;
import com.good.msgsys.exception.CommonException;
import com.good.msgsys.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author junlong
 * @date 2021/1/5 21:47
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if(!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer")) {
            String token = authorization.replace("Bearer ", "");
            Claims claims = jwtUtil.parseJwt(token);
            if (claims != null) {
                request.setAttribute("user_claims", claims);
                return true;
            }
        }
        throw new CommonException(ResultCode.UNAUTHENTICATED);
    }
}
